﻿using System;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace VPLink.WebParts
{
    public class ContentQueryToolPart : ToolPart
    {
        private HtmlInputCheckBox cbxIsLimited;
        private HtmlInputText tbxItemLimit;
        private HtmlGenericControl lblItemLimit;
        private HtmlInputText tbxDetailsPageUrl;
        private HtmlSelect slcSortBy;
        private RadioButtonList radSortOrderList;
        //private RadioButtonList radItemLimitTypeList;

        /// <summary>
        /// Constructor for the class.
        /// </summary>        
        public ContentQueryToolPart()
        {
            this.Title = "Outils de présentation :";
            this.PreRender += new EventHandler(ContentQueryToolPart_PreRender);
        }

        /// <summary>
        /// Create dropdownlist to display lists
        /// </summary>
        override protected void CreateChildControls()
        {
            try
            {
                HtmlTable table = new HtmlTable();
                HtmlTableRow row;
                HtmlTableCell cell;

                HtmlGenericControl divUserDottedLine = new HtmlGenericControl("div");
                divUserDottedLine.Attributes.Add("class", "UserDottedLine");

                // First row
                row = new HtmlTableRow();

                cell = new HtmlTableCell();
                cbxIsLimited = new HtmlInputCheckBox();
                cbxIsLimited.Checked = false;
                cbxIsLimited.Attributes.Add("onclick", string.Format("javascript:toggleItemLimit()"));
                cell.Controls.Add(cbxIsLimited);

                row.Cells.Add(cell);

                cell = new HtmlTableCell();
                HtmlGenericControl lblIsLimited = new HtmlGenericControl("label");
                lblIsLimited.InnerText = "Limiter le nombre d'éléments à afficher";
                cell.Controls.Add(lblIsLimited);

                row.Cells.Add(cell);

                table.Rows.Add(row);

                // Second row
                row = new HtmlTableRow();

                cell = new HtmlTableCell();
                cell.ColSpan = 2;
                lblItemLimit = new HtmlGenericControl("label");
                lblItemLimit.InnerText = "Limitation des éléments: ";
                lblItemLimit.Disabled = true;
                cell.Controls.Add(lblItemLimit);

                tbxItemLimit = new HtmlInputText();
                tbxItemLimit.Disabled = true;
                tbxItemLimit.ID = "tbxItemLimit";
                tbxItemLimit.Style.Add("width", "32px");
                tbxItemLimit.Style.Add("text-align", "right");

                RangeValidator vldItemLimit = new RangeValidator();
                vldItemLimit.MaximumValue = "16000";
                vldItemLimit.MinimumValue = "0";
                vldItemLimit.Type = ValidationDataType.Integer;
                vldItemLimit.ErrorMessage = "La limite d'élément spécifiée n'est pas valide";
                vldItemLimit.Display = ValidatorDisplay.Dynamic;
                vldItemLimit.ControlToValidate = tbxItemLimit.ID;

                cell.Controls.Add(tbxItemLimit);
                cell.Controls.Add(vldItemLimit);
                cell.Controls.Add(divUserDottedLine);

                row.Cells.Add(cell);

                table.Rows.Add(row);

                //    // Third row
                //    row = new HtmlTableRow();

                //        cell = new HtmlTableCell();
                //        cell.ColSpan = 2;
                //        radItemLimitTypeList = new RadioButtonList();
                //        radItemLimitTypeList.Items.Add(new ListItem("Afficher les éléments par groupes de la taille spécifiée.", bool.TrueString));
                //        radItemLimitTypeList.Items.Add(new ListItem("Limiter le nombre total d'éléments retournés à la quantité spécifiée.", bool.FalseString));
                //        cell.Controls.Add(radItemLimitTypeList);

                //    row.Cells.Add(cell);

                //table.Rows.Add(row);

                // Fourth row
                row = new HtmlTableRow();

                cell = new HtmlTableCell();
                cell.ColSpan = 2;
                HtmlGenericControl lblDetailsPageUrl = new HtmlGenericControl("label");
                lblDetailsPageUrl.InnerText = "Url de la page de détails: ";
                cell.Controls.Add(lblDetailsPageUrl);
                cell.Controls.Add(new LiteralControl("<br/>"));

                tbxDetailsPageUrl = new HtmlInputText();
                tbxDetailsPageUrl.Style.Add("width", "176px");
                tbxDetailsPageUrl.Style.Add("font-family", "verdana, arial, sans-serif");
                tbxDetailsPageUrl.Style.Add("font-size", "8pt");
                cell.Controls.Add(tbxDetailsPageUrl);
                cell.Controls.Add(divUserDottedLine);

                row.Cells.Add(cell);

                table.Rows.Add(row);

                // Fifth row
                row = new HtmlTableRow();

                cell = new HtmlTableCell();
                cell.ColSpan = 2;
                HtmlGenericControl lblSortBy = new HtmlGenericControl("label");
                lblSortBy.InnerText = "Critère de tri des éléments : ";
                cell.Controls.Add(lblSortBy);
                cell.Controls.Add(new LiteralControl("<br/>"));

                slcSortBy = new HtmlSelect();
                ListViewWebPart currentWebPart = (ListViewWebPart)ParentToolPane.SelectedWebPart;
                if (currentWebPart != null)
                {
                    Guid activeListID = currentWebPart.ListID;
                    Guid activeWebID = currentWebPart.WebID;

                    if (activeListID != Guid.Empty)
                    {
                        SPFieldCollection fc;
                        if (activeWebID != null && activeWebID != Guid.Empty)
                        {
                            using (SPWeb web = SPContext.Current.Site.OpenWeb(activeWebID))
                            {
                                fc = web.Lists[activeListID].Fields;
                            }
                        }
                        else
                            fc = SPContext.Current.Web.Lists[activeListID].Fields;

                        slcSortBy.Items.Add(new ListItem("Par défaut", string.Empty));
                        foreach (SPField f in fc)
                        {
                            if (f.Sortable && !f.Hidden)
                            {
                                slcSortBy.Items.Add(new ListItem(f.Title, f.InternalName));
                            }
                        }
                        slcSortBy.SelectedIndex = 0;
                        slcSortBy.Disabled = false;
                        lblSortBy.Disabled = false;
                    }
                    else
                    {
                        slcSortBy.Disabled = true;
                        lblSortBy.Disabled = true;
                    }

                }
                cell.Controls.Add(slcSortBy);

                row.Cells.Add(cell);

                table.Rows.Add(row);

                // Fifth row
                row = new HtmlTableRow();

                cell = new HtmlTableCell();
                cell.ColSpan = 2;

                radSortOrderList = new RadioButtonList();
                radSortOrderList.Items.Add(new ListItem("Afficher les éléments par ordre croissant.<br/>(A, B, C ou 1, 2, 3).", bool.TrueString));
                radSortOrderList.Items.Add(new ListItem("Afficher les éléments par ordre décroissant.<br/>(C, B, A ou 3, 2, 1).", bool.FalseString));
                cell.Controls.Add(radSortOrderList);

                row.Cells.Add(cell);

                table.Rows.Add(row);

                Controls.Add(table);

                #region JavaScript

                string script = "<script type=\"text/javascript\">" + Environment.NewLine +
                                "function toggleItemLimit()" + Environment.NewLine +
                                "{" + Environment.NewLine +
                                "    if (!document.getElementById) return;" + Environment.NewLine +
                                string.Format("    var itemLimitTextBox = document.getElementById('{0}');", tbxItemLimit.ClientID) + Environment.NewLine +
                                string.Format("    var itemLimitTextBoxLabel = document.getElementById('{0}')", lblItemLimit.ClientID) + Environment.NewLine +
                                string.Format("    var itemLimitCheckBox = document.getElementById('{0}')", cbxIsLimited.ClientID) + Environment.NewLine +
                                string.Format("    var itemLimitValidator = document.getElementById('{0}')", vldItemLimit.ClientID) + Environment.NewLine +
                                "    if (itemLimitTextBox == null" + Environment.NewLine +
                                "        || itemLimitCheckBox == null" + Environment.NewLine +
                                "        || itemLimitValidator == null" + Environment.NewLine +
                                "        || itemLimitTextBoxLabel == null) return;" + Environment.NewLine +
                                "    itemLimitTextBox.disabled = !itemLimitCheckBox.checked;" + Environment.NewLine +
                                "    itemLimitTextBoxLabel.disabled = !itemLimitCheckBox.checked;" + Environment.NewLine +
                                "    ValidatorEnable(itemLimitValidator, itemLimitCheckBox.checked);" + Environment.NewLine +
                                "}" + Environment.NewLine +
                                "</script>";

                if (!Page.ClientScript.IsStartupScriptRegistered("script"))
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "script", script);
                }

                #endregion
            }
            catch (Exception e)
            {
                Log.Write(e.Message + "\r\n" + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        ///	<summary>
        ///	This method is called by the ToolPane object to apply property changes to the selected Web Part. 
        ///	</summary>
        override public void ApplyChanges()
        {
            // Apply property values here.
            ListViewWebPart currentWebPart = (ListViewWebPart)ParentToolPane.SelectedWebPart;
            if (currentWebPart != null)
            {
                currentWebPart.IsLimited = cbxIsLimited.Checked;
                currentWebPart.ItemLimit = uint.Parse(tbxItemLimit.Value);
                currentWebPart.DetailsPageUrl = tbxDetailsPageUrl.Value;
                currentWebPart.SortBy = slcSortBy.Value;
                //if (radSortOrderList.SelectedItem != null) currentWebPart.SortOrder = bool.Parse(radSortOrderList.SelectedItem.Value);
                //if (radItemLimitTypeList.SelectedItem != null) currentWebPart.ItemLimitType = bool.Parse(radItemLimitTypeList.SelectedItem.Value);
            }
        }

        ///	<summary>
        ///	Initializes ToolPart values. 
        ///	</summary>
        private void ContentQueryToolPart_PreRender(object sender, EventArgs ea)
        {
            try
            {
                ListViewWebPart currentWebPart = (ListViewWebPart)ParentToolPane.SelectedWebPart;
                if (currentWebPart != null)
                {
                    cbxIsLimited.Checked = currentWebPart.IsLimited;
                    tbxItemLimit.Disabled = !cbxIsLimited.Checked;
                    lblItemLimit.Disabled = !cbxIsLimited.Checked;
                    tbxItemLimit.Value = currentWebPart.ItemLimit.ToString();
                    tbxDetailsPageUrl.Value = currentWebPart.DetailsPageUrl;
                    foreach (ListItem item in slcSortBy.Items)
                    {
                        item.Selected = (item.Value == currentWebPart.SortBy.ToString());
                    }
                    foreach (ListItem item in radSortOrderList.Items)
                    {
                        item.Selected = (item.Value == currentWebPart.SortOrder.ToString());
                    }
                    //foreach (ListItem item in radItemLimitTypeList.Items)
                    //{
                    //    item.Selected = (item.Value == currentWebPart.ItemLimitType.ToString());
                    //}
                }
            }
            catch (Exception e)
            {
                Log.Write(e.Message + "\r\n" + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
            }
        }
    }
}